<template>
    <div class="my-editor" :id="id" v-loading.lock.fullscreen="loading" ref="myEditorRef" v-if="!showMode">
    </div>
    <div v-else class="w-e-text-container border_1">
        <div class="w-e-text" v-html="value" ></div>
    </div>
</template>

<script>
import hljs from 'highlight.js';
import wangeditor from 'wangeditor';
import { PublicUploadFileItemZip } from '@/api/PublicServices';
export default {
    name: 'AppEditor',
    props: {
        id: {
            type: String,
            default: function() {
                return 'wangeditor' + +new Date() + ((Math.random() * 1000).toFixed(0) + '');
            }
        },
        value: {
            type: String,
            default: ''
        },
        disabled: {
            type: Boolean,
            default: false
        },
        showMode: {
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '请输入富文本内容'
        },
        config: {
            type: Object,
            default: null
        },
        height: {
            type: Number,
            default: 300
        }
    },
    watch: {
        'value': {
            immediate: true,
            handler(newValue) {
                this.check()
                    .then(pass => {
                        this.myEditor.txt.html(newValue);
                    })
            }
        },
        'disabled': {
            immediate: true,
            handler(newValue) {
                this.check()
                    .then(pass => {
                        if (newValue) {
                            this.myEditor.disable();
                            return;
                        }
                        this.myEditor.enable();
                    })
            }
        }
    },
    data() {
        return {
            finish: false,
            loading: false,
            myEditor: null,
            myEditorContent: null,
            uploadConfig: {
                useDay: 1000,
                path: 'middleground/wangEditor',
                projectId: process.env.VUE_APP_FILE_SERVICE_ID
            },
            editorConfig: {
                zIndex: 11,
                focus: true,
                height: this.height,
                placeholder: this.placeholder,
                showLinkImg: false,
                pasteIgnoreImg: false,
                // showMenuTooltips: false, // 菜单工具栏提示
                menuTooltipPosition: 'down',  // 菜单工具栏提示方向：up/down
                // showFullScreen: false, // 全屏工具栏
                uploadImgMaxSize: 2 * 1024 * 1024,
                uploadVideoMaxSize: 50 * 1024 * 1024 * 1024,
                uploadImgAccept: [ 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp' ],
                uploadVideoAccept: [ 'mp4', 'flv', 'mov', 'mpeg' ],
                uploadImgMaxLength: 20,
                customUploadImg: (resultFiles, insertImgFn) => {
                    this.uploadFiles(resultFiles, insertImgFn);
                },
                customUploadVideo: (resultFiles, insertVideoFn) => {
        
                    this.uploadVideoFiles(resultFiles, insertVideoFn);
                },
                customAlert: (s, t) => {
                    this.$message({
                        message: s,
                        type: t ? t : 'info'
                    });
                },
                onchangeTimeout: 200,
                onchange: (value) => { // 配置 onchange 回调函数
                    this.myEditorContent = value;
                    this.$emit('input', this.myEditorContent);
                }
            },
        }
    },
    methods: {
        setHtml(val) {
            this.check()
                .then(pass => {
                    this.myEditor.txt.html(val);
                })
        },
        getHtml() {
            if (this.myEditor) {
                return this.myEditor.txt.html();
            }
            return '';
        },
        getText() {
            if (this.myEditor) {
                return this.myEditor.txt.text();
            }
            return '';
        },
        clear() {
            if (this.myEditor) {
                this.myEditor.txt.clear();
            }
        },
        check() {
            return new Promise(resolve => {
                const timer = setInterval(() => {
                    if (this.finish) {
                        clearInterval(timer);
                        resolve(true);
                    }
                }, 10);
            })
        },
        init() {
            const _this = this;
            const myEditor = new wangeditor(`#${this.id}`);

            const config = Object.assign(_this.editorConfig, this.config);
            for (let key in config) {
                myEditor.config[key] = config[key];
            }
            myEditor.highlight = hljs;
            myEditor.create();
            _this.myEditor = myEditor;
            _this.finish = true;
            _this.$emit('init', true); // 初始化完成
        },
        uploadFiles(files, insert) {
            var formData = new FormData();
            for (let key in this.uploadConfig) {
                formData.append(key, this.uploadConfig[key]);
            }
            files.forEach((item, index) => {
                formData.append('file', item, item.name )
            });
            this.loading = true;
            PublicUploadFileItemZip(formData)
            .finally(() => this.loading = false)
            .then(data => {
                if (data && data.code == 200) {
                    data.data.forEach(result => {
                            insert(result.ip + '/' + result.fileUrl);                   
                    })
                } else {
                    failure(data.msg);
                }
            })
            .catch(error => {
                failure(error);
            })
        },
        uploadVideoFiles(files, insert) {
            var formData = new FormData();
            for (let key in this.uploadConfig) {
                formData.append(key, this.uploadConfig[key]);
            }
            files.forEach((item, index) => {
                formData.append('file', item, item.name )
            });
            this.loading = true;
            PublicUploadFileItemZip(formData)
            .finally(() => this.loading = false)
            .then(data => {
                if (data && data.code == 200) {
                    data.data.forEach(result => {
                        // insert(result.ip + '/' + result.fileUrl);
                        this.myEditor.txt.append('<video src="'+ result.ip + '/' + result.fileUrl+'" controls="controls"></video>');                   
                    })
                } else {
                    failure(data.msg);
                }
            })
            .catch(error => {
                failure(error);
            })
        }
    },
     uploadSuccess (e) {        
        const that = this
        const getImages = async _ => {
          let f = function (i) {
            let param = new FormData()
            param.append('file', e.target.files[i])
            for (let key in that.uploadConfig) {
              param.append(key, that.uploadConfig[key])
            }
            return PublicUploadFileItemZip(formData)
            .finally(() => this.loading = false)
            .then(data => {
                if (data && data.code == 200) {
                    data.data.forEach(result => {
                        insert(result.ip + '/' + result.fileUrl);
                    })
                } else {
                    failure(data.msg);
                }
            })
            .catch(error => {
                failure(error);
            })
          }
          for (let i = 0; i < e.target.files.length; i++) {
            await f(i)
          }
          this.$refs.referenceUpload.value = null
        }
        getImages()
      },
    mounted() {
        if (this.showMode) return;
        this.init();
    },
    beforeDestroy() {
        if (!this.myEditor) return;
        this.myEditor.destroy();
        this.finish = false;
        this.myEditor = null;
    }
}
</script>

<style lang="scss" scoped>
@import '~highlight.js/styles/monokai-sublime.css';
.border_1 {
    border: 1px solid #c9d8db;

    > div {
        min-height: 100px;
        resize: vertical;
    }
}

// ::v-deep .w-e-text-container {
//     height: auto !important;
// }

// ::v-deep .w-e-text-container .w-e-text {
//     resize: vertical;
//     min-height: 100px;
// }

// ::v-deep .w-e-full-screen-editor .w-e-text-container {
//     height: calc(100% - 42px) !important;
// }

// ::v-deep .w-e-full-screen-editor .w-e-text-container .w-e-text {
//     resize: vertical;
// }
</style>